package com.dapeng.lmssim.client;

import feign.Request;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 这里不要使用@Configuration声明，如果加上此注解，以下配置会覆盖默认，对所有feign client的都生效
 *
 * @author songkaizong
 */
public class IMServiceConfiguration {
    /**
     * 当接口响应状态不是2XX时，会调用此方法,可解析针对im-service的自定义异常
     *
     * @return
     */
    @Bean
    public ErrorDecoder errorDecoder() {
        return new ErrorDecoder.Default() {
            @Override
            public Exception decode(String methodKey, Response response) {
                if (response.status() >= 400 && response.status() < 500) {
                    try {
                        if (response.body() != null) {
                            String body = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
                            return new IMServiceException(body);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return super.decode(methodKey, response);
            }
        };
    }

    /**
     * 针对im-service的超时配置
     *
     * @return
     */
    @Bean
    public Request.Options options() {
        return new Request.Options(2, TimeUnit.SECONDS, 10, TimeUnit.SECONDS, false);
    }

    // 此外还有编码，解码，request拦截器，log配置
}
